package com.hyjx.framework.uc.menu;

import com.hyjx.framework.common.util.StringHelper;
import com.hyjx.framework.service.RightManager;
import com.hyjx.framework.uc.subsys.SubsysModel;
import com.hyjx.framework.uc.subsys.SubsysService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 菜单控制器
 *
 * @author Peter
 */
@Controller
@RequestMapping("/menu")
public class MenuController {
    @Resource
    private MenuService service;
    @Resource
    private SubsysService subsysService;
    
    /**
     * 进入到信息查询页
     *
     * @return
     */
    @RequestMapping(value = "/gotoList", method = {RequestMethod.GET, RequestMethod.POST})
    public String gotoList(HttpServletRequest request) {
        return "/framework/uc/menu/list";
    }
    
    /**
     * 执行客户查询操作
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(MenuModel model, HttpServletRequest request) {
        return service.queryList(model);
    }
    
    /**
     * 跳转到增加页
     *
     * @return
     *
     * @throws SQLException
     */
    @RequestMapping(value = "/gotoAdd", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView gotoAdd(HttpServletRequest request, MenuModel model) throws SQLException {
        ModelAndView mav = new ModelAndView("/framework/uc/menu/add");
        String addsub = request.getParameter("addsub");
        
        if (addsub == null) {
            String maxroot = null;
            model.setMenu_name("");
            model.setMenu_desc("");
            try {
                maxroot = service.getrootmax(null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            model.setOrder_no(maxroot);
            maxroot = maxroot.length() == 1 ? "0" + maxroot : maxroot;
            model.setMenu_code(maxroot);
            model.setMenu_code_full(model.getMenu_code() + ".");
            model.setMenu_parent_code(null);
            model.setFunc_entra(null);
        } else {
            
            if (model.getMenu_code() == null) {//
                //String subsysId=model.getSubsys_id();
                String sysid = request.getParameter("sysid");
                String maxroot = service.getNewCode(sysid, model.getMenu_code());
                model.setOrder_no("10");
                model.setMenu_parent_code(null);
                model.setSubsys_id(sysid);
                model.setMenu_code(maxroot);
                model.setMenu_code_full(maxroot + ".");
                model.setFunc_entra(null);
                model.setMenu_name("");
                model.setMenu_desc("");
            } else {
                model = service.getInfoById(model);
                if (model == null)
                    return mav;
                String mc = model.getMenu_code();
                String subsysId = model.getSubsys_id();
                String maxcode = service.getNewCode(subsysId, model.getMenu_code());
                model.setSubsys_id(subsysId);
                model.setOrder_no("10");
                model.setMenu_parent_code(model.getMenu_code());
                model.setMenu_code(maxcode);
                model.setMenu_code_full(mc + "." + model.getMenu_code() + ".");
                model.setFunc_entra(null);
                model.setMenu_name("");
                model.setMenu_desc("");
            }
            
        }
        mav.addObject("model", model);
        return mav;
    }
    
    /**
     * 增加信息
     *
     * @param MenuModel
     * @return
     *
     * @throws SQLException
     */
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    @ResponseBody
    public String doAdd(MenuModel model) throws SQLException {
        MenuModel pmodel = new MenuModel();
        if (model.getMenu_code().length() > 2) {//二级及以下子节点添加，需要修改父属性的此值
            pmodel.setMenu_code(model.getMenu_parent_code());
            pmodel = service.getInfoById(pmodel);
            pmodel.setIs_leaf_node("N");
            service.edit(pmodel);
        }
        model.setIs_leaf_node("Y");
        model.setLevelId(model.getMenu_parent_code() == null ? "" : model.getMenu_code());
        if (model.getMenu_parent_code() == null || "".equals(model.getMenu_parent_code())) {
            model.setMenu_parent_code("#");
        }
        
        if (service.add(model)) {
            String levelId = "";
            if ("#".equals(model.getMenu_parent_code())) {
                SubsysModel sm = subsysService.getSubsysById(model.getSubsys_id());
                levelId = String.format("%03d", getSubSysNo(sm.getSubsys_id()));
            } else {
                levelId = pmodel.getLevelId();
            }
            /*String levelId = ("#".equals(model.getMenu_parent_code()))?"":pmodel.getLevelId();
			SubsysModel sm = subsysService.getSubsysById(model.getSubsys_id());
			levelId = String.format("%03d",Integer.parseInt(sm.getOrder_no()))+ levelId ;*/
            calculageLevelId(model, levelId);
            RightManager.init(2);
            return "success";
        } else {
            return "failure";
        }
    }
    
    /**
     * 跳转到修改页�?
     * request
     *
     * @return
     */
    @RequestMapping(value = "/gotoEdit", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView gotoEdit(HttpServletRequest request) {
        String id = request.getParameter("id");
        MenuModel model = new MenuModel();
        model.setMenu_code(id);
        model = service.getInfoById(model);
        ModelAndView mav = new ModelAndView("/framework/uc/menu/edit");
        mav.addObject("model", model);
        return mav;
    }
    
    /**
     * 修改信息
     *
     * @param model
     * @return
     *
     * @throws SQLException
     */
    @RequestMapping(value = "/doEdit", method = RequestMethod.POST)
    @ResponseBody
    public String doEdit(MenuModel model) throws SQLException {
        try {
            model.setLevelId(model.getMenu_code() + model.getOrder_no());
            MenuModel pmodel = new MenuModel();
            if (model.getMenu_code().length() > 2) {//二级及以下子节点添加，需要修改父属性的此值
                pmodel.setMenu_code(model.getMenu_parent_code());
                pmodel = service.getInfoById(pmodel);
            }
            if (service.edit(model) > 0) {
                //String levelId = ("#".equals(model.getMenu_parent_code()))?"":pmodel.getLevelId()==null?"":pmodel.getLevelId();
                model = service.getInfoById(model);
                
                //levelId = String.format("%03d",Integer.parseInt(sm.getOrder_no()))+ levelId ;
                //calculageLevelId(model,levelId);
                String levelId = "";
                if ("#".equals(model.getMenu_parent_code())) {
                    SubsysModel sm = subsysService.getSubsysById(model.getSubsys_id());
                    levelId = String.format("%03d", getSubSysNo(sm.getSubsys_id()));
                } else {
                    levelId = pmodel.getLevelId();
                }
                calculageLevelId(model, levelId);
                RightManager.init(2);
			/*	String levelId = (model.getMenu_parent_code()==null||"".equals(model.getMenu_parent_code()))?"":pmodel.getLevelId()==null?"":pmodel.getLevelId();
				model = service.getInfoById(model);
				SubsysModel sm = subsysService.getSubsysById(model.getSubsys_id());
				levelId = String.format("%03d",Integer.parseInt(sm.getOrder_no()))+ levelId ;
				calculageLevelId(model,levelId);
				RightManager.init(2);*/
                return "success";
            } else {
                return "failure";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        }
    }
    
    /**
     * 删除信息
     * request
     *
     * @return
     */
    @RequestMapping(value = "/gotoDelete", method = RequestMethod.POST)
    @ResponseBody
    public String gotoDelete(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (service.delete(ids) > 0) {
            RightManager.init(2);
            return "success";
        } else {
            return "failure";
        }
    }
    
    /**
     * 信息查看
     * request
     *
     * @return
     */
    @RequestMapping(value = "/gotoView", method = RequestMethod.GET)
    public ModelAndView gotoView(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/uc/menu/view");
        return mav;
    }
    
    /**
     * 生成菜单树
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/menutree", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String menuTree(HttpServletRequest request, MenuModel model) {
        try {
            return service.queryTree(model);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 定向到树页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/gotoMenutree", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView gotoMenutree(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/uc/menu/menutree");
        return mav;
    }
    
    @RequestMapping(value = "/gotoMenuFunc", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView gotoFunc(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/uc/menu/menu_func");
        MenuFunc mf = new MenuFunc();
        mf.setMenu_code(request.getParameter("menu_code"));
        mav.addObject("model", mf);
        return mav;
    }
    
    @RequestMapping(value = "/queryMenuFunc", method = RequestMethod.POST)
    @ResponseBody
    public String queryFuncList(MenuFunc model, HttpServletRequest request) {
        return service.queryFuncList(model);
    }
    
    @RequestMapping(value = "/doAddMenuFunc", method = RequestMethod.POST)
    @ResponseBody
    public String doAddMenuFunc(MenuFunc model) {
        model.setOperate_id(StringHelper.getPrimaryKey());
        if (service.doAddMenuFunc(model)) {
            RightManager.init(2);
            return "success";
        } else {
            return "failure";
        }
    }
    
    @RequestMapping(value = "/doEditMenuFunc", method = RequestMethod.POST)
    @ResponseBody
    public String doEditMenuFunc(MenuFunc model) {
        if (service.doEditMenuFunc(model)) {
            RightManager.init(2);
            return "success";
        } else {
            return "failure";
        }
    }
    
    @RequestMapping(value = "/doDeleteMenuFunc", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String doDeleteMenuFunc(MenuFunc model) {
        if (service.doDeleteMenuFunc(model)) {
            RightManager.init(2);
            return "success";
        } else {
            return "failure";
        }
    }
    
    /**
     * 计算最大的层级码
     *
     * @param model
     * @param parenLlevelId
     */
    public void calculageLevelId(MenuModel model, String parenLlevelId) {
        List<MenuModel> list = service.getlListByFather(model);//同级节点
        Collections.sort(list, new MenuModelSortAsc());
        int j = 1;
        for (MenuModel mm : list) {
            String levelId = String.format("%03d", j);
            mm.setLevelId((parenLlevelId == null ? "" : parenLlevelId) + levelId);
            service.edit(mm);
            MenuModel m = new MenuModel();
            m.setMenu_parent_code(mm.getMenu_code());
            service.calcLevelId(m, mm.getLevelId() == null ? "" : mm.getLevelId());//递归子孙节点
            j++;
        }
    }
    
    private class MenuModelSortAsc implements Comparator<MenuModel> {
        @Override
        public int compare(MenuModel o1, MenuModel o2) {
            if (!o1.getOrder_no().equals(o2.getOrder_no()))
                return Integer.parseInt(o1.getOrder_no()) - Integer.parseInt(o2.getOrder_no());
            else
                return o1.getMenu_code().compareTo(o2.getMenu_code());
        }
    }
    
    /**
     * 检查是否存在
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/checkExist", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String selectExistCode(MenuFunc model) {
        List<MenuFunc> list = service.selectFuncList(model);
        if (list == null || list.size() == 0) {
            return "noexist";
        } else if (list.size() == 1) {
            MenuFunc tmp = list.get(0);
            if (tmp.getOperate_id().equals(model.getOperate_id()))
                return "noexist";
            else
                return "exist";
        } else
            return "exist";
    }
    
    /**
     * 检查菜单编码是否存在
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkMenuCodeExist", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String selectExistMenuCode(HttpServletRequest request) {
        
        String menuId = request.getParameter("menuCode");
        MenuModel model = new MenuModel();
        model.setMenu_code(menuId);
        model = service.getInfoById(model);
        if (model == null) {
            return "noexist";
        } else {
            return "exist";
        }
    }
    
    public int getSubSysNo(String subsysid) {
        SubsysModel model = new SubsysModel();
        List<SubsysModel> list = subsysService.getAllSubsys(model);
        
        if (list == null || list.size() == 0)
            return 0;
        else {
            for (int i = 0; i < list.size(); i++) {
                if (subsysid.equals(list.get(i).getSubsys_id()))
                    return i;
            }
        }
        
        return 0;
    }
    
}